package com.jindu.producer.finance.controller;

import com.jindu.kernel.page.AlphaPage;
import com.jindu.kernel.result.JsonResult;
import com.jindu.kernel.utils.AlphaBeanUtils;
import com.jindu.kernel.utils.DateUtils;
import com.jindu.kernel.utils.IdGenerator;
import com.jindu.kernel.utils.RandomUtil;
import com.jindu.producer.finance.api.UserInterface;
import com.jindu.producer.finance.jpa.HightechJpa;
import com.jindu.producer.finance.model.CContentEntity;
import com.jindu.producer.finance.model.FHightechEntity;
import com.jindu.producer.finance.model.SUsersEntity;
import com.jindu.producer.finance.shiro.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jarvis
 * @date 2018/10/18
 */
@Api(description = "高新评测结果管理", tags = "HightechController", basePath = "/highTech")
@RestController
@RequestMapping(value = "/highTech",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class HightechController {

    @Autowired
    HightechJpa hightechJpa;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据国高的ID，查询国高评测的信息", notes = "返回单个国高评测的信息")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public JsonResult<FHightechEntity> get(@RequestParam String id){
        return JsonResult.getSuccessResult(hightechJpa.findById(id));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据用户的ID，查询国高评测的信息", notes = "返回该用户填写的国高评测的信息")
    @RequestMapping(value = "getByUserId",method = RequestMethod.GET)
    public JsonResult<FHightechEntity> getByUserId(ServletRequest request){

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        if(authorization!=null) {
            String userId = JwtUtils.getUserId(authorization);
            return JsonResult.getSuccessResult(hightechJpa.findByUserId(userId));
        }else{
            return JsonResult.getFailureByNoAuthorization();
        }
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据分页参数，查询国高的信息填写的信息", notes = "返回企业国高的信息集合")
    @RequestMapping(value = "getAll",method = RequestMethod.GET)
    public JsonResult<AlphaPage<FHightechEntity>> getAll(@RequestParam(value = "pageNo",defaultValue = "0") Integer pageNo,
                                                         @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                                         @RequestParam(value = "name", required = false) String name){

        Specification querySpecifi = (Specification<FHightechEntity>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if(name != null){
                predicates.add(criteriaBuilder.like(root.get("name"),"%"+name+"%"));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Page<FHightechEntity> entities=hightechJpa.findAll(querySpecifi,new PageRequest(pageNo, pageSize,sort));
        return new AlphaPage<>(entities).toJsonResult();
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "保存国高评测的信息", notes = "保存国高评测的信息")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public JsonResult<FHightechEntity> save(ServletRequest request,
                                            @RequestBody FHightechEntity hightechEntity){

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");

        if(authorization!=null) {
            String userId = JwtUtils.getUserId(authorization);
            FHightechEntity fHightechEntity=hightechJpa.findById(hightechEntity.getId());

            if(fHightechEntity == null){
                hightechEntity.setId(IdGenerator.uuid());
                Integer orgCode= RandomUtil.getNum(100000,999999);
                hightechEntity.setUserId(userId);
                hightechEntity.setOrgId(orgCode);
                hightechEntity.setCreateTime(new Timestamp(DateUtils.getCurrentTime()));
                hightechEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
                hightechEntity.setCreateId(userId);
                hightechEntity.setModifyId(userId);
                return JsonResult.getSuccessResult(hightechJpa.saveAndFlush(hightechEntity));

            }else {
                hightechEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
                BeanUtils.copyProperties(hightechEntity,fHightechEntity, AlphaBeanUtils.getNullPropertyNames(hightechEntity));
                return JsonResult.getSuccessResult(hightechJpa.saveAndFlush(fHightechEntity));
            }
        }else {
            return JsonResult.getFailureByNoAuthorization();
        }



    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "删除国高评测的信息", notes = "根据ID,删除数据")
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public JsonResult<Integer> delete(@RequestBody String id){
        return JsonResult.getSuccessResult(hightechJpa.deleteById(id));
    }


}
